using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
using System.Linq;

namespace ClubWebsite
{
    public partial class UserLogin : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                // Hide all controls by default
                HideAllControls();

                // Only display the necessary controls to allow the user to log in or out
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    btnLogin.Text = "Logout";
                    btnLogin.Visible = true;
                }
                else
                {
                    btnLogin.Text = "Login";
                    btnLogin.Visible = true;
                }
            }
        }

        private void HideAllControls()
        {
            btnLogin.Visible = false;
            litEmail.Visible = false;
            txtEmail.Visible = false;
            litPassword.Visible = false;
            txtPassword.Visible = false;
            btnOK.Visible = false;
            lblError.Visible = false;
            litInformation.Visible = false;
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            HideAllControls();

            // Login the user if their details are correct
            if ((txtEmail.Text.Trim().Length == 0) || (txtPassword.Text.Trim().Length == 0))
            {
                btnLogin.Text = "Login";
                lblError.Text = "Both fields must be entered.";
                lblError.Visible = true;
                btnLogin.Visible = true;
            }
            else
            {
                using (MainDataClassesDataContext databaseDataContext = Functions.GetDatabaseDataContext())
                {
                    bool userExists = databaseDataContext
                        .Users
                        .Any(u => u.Email.ToLower() == txtEmail.Text.Trim().ToLower());

                    // Check that the email address exists
                    if (!userExists)
                    {
                        lblError.Text = "The email address is not registered.";
                        lblError.Visible = true;
                        litInformation.Text = System.Text.RegularExpressions.Regex.Replace(litInformation.Text, @"(?<=\>)\w*(?=\<)", "Click here to register the email address.");
                        litInformation.Text = System.Text.RegularExpressions.Regex.Replace(litInformation.Text, @"(?<=href="")\w*(?=\"")", "/everyonesclub/register/Default.aspx?Email=" + HttpUtility.HtmlEncode(txtEmail.Text.Trim()));
                        litInformation.Visible = true;
                        btnLogin.Visible = true;
                        return;
                    }

                    // Check that the email address is confirmed
                    Guid userID = databaseDataContext
                        .Users
                        .Where(u => u.Email.ToLower() == txtEmail.Text.Trim().ToLower())
                        .Select(u => u.ID)
                        .Single();
                    bool emailConfirmed = databaseDataContext
                        .Users
                        .Any(u => (u.ID == userID)
                            && (u.EmailConfirmed != null)
                            && ((byte)u.EmailConfirmed) != 0);
                    if (!emailConfirmed)
                    {
                        // The address is not confirmed, go to the confirmation page
                        Response.Redirect("/everyonesclub/confirmregistration/Default.aspx?Email=" + HttpUtility.HtmlEncode(txtEmail.Text.Trim()));
                        return;
                    }

                    // Check that the login details are cocrrect
                    bool passwordMatches = databaseDataContext
                        .Users
                        .Any(u => (u.ID == userID)
                            && (u.Password == txtPassword.Text.Trim()));
                    if (passwordMatches)
                    {
                        // Login details are correct, log in the user
                        FormsAuthentication.SetAuthCookie(userID.ToString(), false);
                        Response.Redirect(Request.RawUrl.ToString());
                    }
                    else
                    {
                        // Login details are incorrect
                        btnLogin.Text = "Login";
                        btnLogin.Visible = true;
                        lblError.Text = "Details were incorrect. Please try again.";
                        lblError.Visible = true;
                        litInformation.Text = System.Text.RegularExpressions.Regex.Replace(litInformation.Text, @"(?<=\>)\w*(?=\<)", "Click here if you've forgotten your password.");
                        litInformation.Text = System.Text.RegularExpressions.Regex.Replace(litInformation.Text, @"(?<=href="")\w*(?=\"")", "/everyonesclub/forgotpassword/Default.aspx?Email=" + HttpUtility.HtmlEncode(txtEmail.Text.Trim()));
                        litInformation.Visible = true;
                    }
                }
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (btnLogin.Text == "Logout")
            {
                FormsAuthentication.SignOut();
                Response.Redirect(Request.RawUrl.ToString());
            }
            else
            {
                HideAllControls();
                litEmail.Visible = true;
                txtEmail.Visible = true;
                litPassword.Visible = true;
                txtPassword.Visible = true;
                txtEmail.Text = "";
                txtPassword.Text = "";
                btnOK.Visible = true;
                ((Default)Page.Master).ScriptManager.SetFocus(txtEmail);
                ((Default)Page.Master).DefaultButton = btnOK.UniqueID;
            }
        }
    }
}